package com.ydx.demo.controller;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@CrossOrigin(origins = "*")
public class ImageController {

    @GetMapping("/photo/webImage/{folderName}/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String folderName, @PathVariable String filename){
        Path imagePath = Paths.get("D:/photo/webImage",folderName,filename);
        Resource resource;

        try{
            resource = new UrlResource(imagePath.toUri());

            if (resource.exists() && resource.isReadable()){
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);//设置图片类型
                return  new ResponseEntity<>(resource,headers,HttpStatus.OK);
            }else{
                System.out.println("找不到文件" + filename);
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            System.out.println("URL: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
